package com.prinxchengshan.reportbase.Utils;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ExcelUtil {

    public static  String[] ExcelToArray(String fileName){
        String local_path = System.getProperty("user.dir");
        //获取当前用户的当前工作目录
        String path = local_path+"\\src\\main\\resources\\" + fileName;
        String sheetName = "Sheet1";
        String[] dataArray = null;

        try (FileInputStream fis = new FileInputStream(path);
             Workbook workbook = new XSSFWorkbook(fis)) {

            Sheet sheet = workbook.getSheet(sheetName);
            List<String> data = new ArrayList<>();

            for (Row row : sheet) {
                for (Cell cell : row) {
                    String cellValue = cell.getStringCellValue();
                    data.add(cellValue);
                }
            }

            dataArray = data.toArray(new String[0]);


        } catch (IOException e) {
            e.printStackTrace();
        }
        return dataArray;
    }


    public static void writeExcel(XSSFWorkbook xssfWorkbook,String fileName) throws IOException {
        String local_path = System.getProperty("user.dir");
        //获取当前用户的当前工作目录
        String path = local_path+"\\src\\main\\resources\\"+fileName;
        //添加上文件的路径，组成文件的绝对路径
        File file=new File(path);
        FileOutputStream fileOutputStream=new FileOutputStream(file);
        xssfWorkbook.write(fileOutputStream);
        //通过流的方式写入到文件中中
        fileOutputStream.close();
        //使用完成之后要记得关闭这个流
    }
}
